using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class UI_ImageFade : MonoBehaviour
{
    [SerializeField] private Image _fadeImage;
    [SerializeField] private float _playerDeadFadeDuration = .5f;
    [SerializeField] private float _playerDeadFadeStartAplah = 0f;
    [SerializeField] private float _playerDeadFadeEndAplah = 1f;
    private void OnEnable()
    {
        EventCenter.AddEventListener<float, Action>(EventName.PlayerSlectFail, HandlePlayerSelectFail);
    }   
    private void OnDisable()
    {
        EventCenter.RemoveEventListener<float, Action>(EventName.PlayerSlectFail, HandlePlayerSelectFail);
    }
    private void HandlePlayerSelectFail(float responseDuration, Action callback)
    {
        _fadeImage.enabled = true;
        StartCoroutine(PlayerSelectFailCo(_playerDeadFadeDuration, responseDuration, _playerDeadFadeStartAplah, _playerDeadFadeEndAplah, callback));
    }
   
    private IEnumerator PlayerSelectFailCo(float duration, float responseDuration, float startAlpah, float endAlpah, Action callback)
    {
        Player.Instance.PlayerInput.Disable();
        yield return new WaitForSeconds(responseDuration);

        yield return StartCoroutine(FadeInCo(duration, startAlpah, endAlpah));

        callback?.Invoke();

        yield return new WaitForSeconds(.5f);
        yield return StartCoroutine(FadeOutCo(duration, endAlpah, startAlpah));

        Player.Instance.PlayerInput.Enable();
    }
    private IEnumerator FadeInCo(float duration, float startAlpah, float endAlpah)
    {
        Color startColor = _fadeImage.color;
        float timer = 0;
        while (timer < duration)
        {
            timer += Time.deltaTime;
            startColor.a = Mathf.Lerp(startAlpah, endAlpah, timer / duration);

            _fadeImage.color = startColor;
            yield return null;
        }
        startColor.a = endAlpah;
        _fadeImage.color = startColor;
    }
    private IEnumerator FadeOutCo(float duration, float startAlpah, float endAlpah)
    {
        Color startColor = _fadeImage.color;
        float timer = 0;
        while (timer < duration)
        {
            timer += Time.deltaTime;
            startColor.a = Mathf.Lerp(startAlpah, endAlpah, timer / duration);

            _fadeImage.color = startColor;
            yield return null;
        }
        startColor.a = endAlpah;
        _fadeImage.color = startColor;
    }
}

